import 'dart:math';

import 'package:flutter/material.dart';
import 'package:x3_charts_core/model/annular_disc_chart_model.dart';

///**
///* @author hrongyong
///* @date   2/4/21
///* @email hrongyong@gmail.com
///* Description:  环形圆盘
///*/
class AnnularDiscChartPainter extends CustomPainter {
  List<AnnularDiscChartModel> chartList;

  ///动画数值
  final Animation<double> repaint;

  AnnularDiscChartPainter({@required this.chartList, this.repaint}) : super(repaint: repaint);

  ///最大半径
  double maxRadius = 0.0;

  ///间隔大小
  double intervalSize;

  ///每部分的宽度
  double eachWidth = 0.0;

  Paint fillPaint = Paint()..style = PaintingStyle.stroke;

  @override
  void paint(Canvas canvas, Size size) {
    maxRadius = min(size.width / 2, size.height / 2);
    eachWidth = maxRadius / chartList.length;
    intervalSize = eachWidth / 4;
    eachWidth = eachWidth * 0.75;

    ///移动画布中心
    canvas.translate(size.width / 2, size.height / 2);

    ///绘画圆环
    drawAnnularDisc(canvas, size);
  }

  drawAnnularDisc(Canvas canvas, Size size) {
    canvas.save();
    canvas.rotate(-pi / 2);
    int index = chartList.length - 1;
    for (int i = 0; i < chartList.length; i++) {
      double radius = (eachWidth + intervalSize) * (i + 1);
      var rect = Rect.fromCenter(center: Offset(0, 0), height: radius * 2 - eachWidth, width: radius * 2 - eachWidth);
      canvas.drawArc(
          rect,
          0,
          2 * pi * chartList[index].percentage * repaint.value,
          false,
          fillPaint
            ..color = chartList[index].color
            ..strokeWidth = eachWidth);
      index--;
    }
    canvas.restore();
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
